/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gestores.janelas;

import java.io.File;

/**
 * Classe FSTreeModel
 *
 * Descrição:
 *  Modelo de arquivos para JTree
 *
 */
public class FSTreeModel extends AbstractTreeModel {

    private File raiz;

    public FSTreeModel(File rootDirectory) {
            raiz = rootDirectory;
    }

    public Object getRoot() {
        return raiz;
    }

    public Object getChild(Object parent, int index) {
        File directory = (File) parent;
        String[] children = directory.list();
        return new TreeFile(directory, children[index]);
    }

    public int getChildCount(Object parent) {
        File File = (File) parent;
        if (File.isDirectory()) {
            String[] FileList = File.list();
            if (FileList != null) {
                return File.list().length;
            }
        }
        return 0;
    }

    public boolean isLeaf(Object node) {
        File File = (File) node;
        return !File.isDirectory();
    }

    public int getIndexOfChild(Object parent, Object child) {
        File directory = (File) parent;
        File File = (File) child;
        String[] children = directory.list();
        for (int i = 0; i < children.length; i++) {
            if (File.getName().equals(children[i])) {
                return i;
            }
        }
        return -1;
    }

    private class TreeFile extends File {

        public TreeFile(File parent, String child) {
            super(parent, child);
        }

        @Override
        public String toString() {
            return getPath();
        }
    }
}
